import 'dart:io';
import 'package:archive/archive.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:path_provider/path_provider.dart';

class Hotfix {
  static Future<void> exec(File bundle) async {
    if (!Platform.isAndroid) throw UnimplementedError();
    Archive archive = ZipDecoder().decodeBytes(bundle.readAsBytesSync());
    for (ArchiveFile file in archive) {
      String path = (await getApplicationDocumentsDirectory()).path;
      if (file.isFile) {
        File dist = File('$path/${file.name}');
        if (dist.existsSync()) dist.deleteSync();
        dist
          ..createSync(recursive: true)
          ..writeAsBytesSync(file.content);
      } else {
        Directory('$path/${file.name}').createSync(recursive: true);
      }
    }
  }

  static Future<void> hotfix() async {
    // try {
    //   Uri uri = Uri.http('fs.wxdesign.net', '/bundle.zip');
    //   String path = (await getTemporaryDirectory()).path;
    //   File dist = File('$path/bundle.zip');
    //   if (dist.existsSync()) {
    //     Hotfix.exec(dist);
    //     ToastUtil.showMessageToast("更新完毕,请重新打开APP");
    //     dist.deleteSync();
    //     return;
    //   }
    //   HttpClient client = HttpClient();
    //   HttpClientRequest request = await client.getUrl(uri);
    //   HttpClientResponse response = await request.close();
    //   ToastUtil.showMessageToast("下载中...\n ${uri.toString()}");
    //   await response.pipe(dist.openWrite());
    //   await Hotfix.exec(dist);
    //   ToastUtil.showMessageToast("更新完毕,请重新打开APP");
    //   dist.deleteSync();
    // } catch (err) {
    //   ToastUtil.showMessageToast("${err.toString()}");
    // }
  }
}
